<!DOCTYPE html>
<html lang="en" style="background: #FAFAFA!important">
<head>
    <meta charset="UTF-8">
    <title>在线文档转换工具</title>
    <!-- 引入 layui.css -->
    <link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;border-color: #b9b5b5;">
    <legend><h3>在线文档转换工具</h3></legend>
</fieldset>

<div class="layui-bg-gray" style="padding: 50px 100px;">
    <div class="layui-row">
        <div class="layui-col-xs6 layui-col-md12">
            <div class="grid-demo grid-demo-bg2">
                <div class="layui-panel">
                    <div style="padding: 50px 30px; text-align: center">
                        <!--第一步-->
                        <div id="step-1">
                            <form class="layui-form" action="">
                                <div class="layui-form-item">
                                    <div class="layui-input-block" style="margin-left: 0;">
                                        <input type="radio" name="type" value="1" title="PDF转Word" checked="" lay-filter="filter">
                                        <input type="radio" name="type" value="2" title="PDF转图片" lay-filter="filter">
                                        <input type="radio" name="type" value="3" title="WORD转PDF" lay-filter="filter">
                                    </div>
                                </div>
                            </form>
                            <div class="layui-upload-drag" id="document">
                                <div id="content">
                                    <i class="layui-icon"></i>
                                    <p style="margin-top: 15px">点击上传，或将文件拖拽到此处</p>
                                    <p style="margin-top: 35px;font-size: 12px;">文件大小不能超过100MB</p>
                                </div>
                            </div>
                            <div id="choose" style="display: none">
                                <p id="tip" style="display: none;color: #5FB878;">恭喜，您已转换完成！</p>
                                <img style="display: none;margin: 15px;" id="pdf" src="/images/PDF.png">
                                <img style="display: none;margin: 15px;" id="word" src="/images/WORD.png">
                                <img style="display: none;margin: 15px;" id="zip" src="/images/Zip.png">
                                <p style="margin-bottom: 15px" id="name"></p>
                                <p id="compete" style="display: none;margin-top: 30px">
                                    <button id="download" class="layui-btn layui-btn-sm">下载</button>
                                    <button id="delete" class="layui-btn layui-btn-danger layui-btn-sm">删除</button>
                                    <button onclick="reUpload()" class="layui-btn layui-btn-primary layui-btn-sm">返回</button>
                                </p>
                                <div style="margin: 30px auto;width: 200px;" class="layui-progress" lay-showpercent="true" lay-filter="demo">
                                    <div class="layui-progress-bar" lay-percent="0%"></div>
                                </div>
                                <button id="transform" class="layui-btn layui-btn-primary layui-btn-sm layui-border-green">开始转换</button>
                                <button id="reUpload" onclick="reUpload()" class="layui-btn layui-btn-primary layui-btn-sm layui-border-black" >重新上传</button>
                            </div>
                        </div>
                        <!--第二步-->
                        <div id="step-2" style="display: none">
                            <img class="conversion" src="/images/文件转换.png">
                        </div>
                    </div>
                </div>
                <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;color: #7ea08b;">
                    <i class="layui-icon layui-icon-find-fill"></i> 操作指南：点击选择文档或拖动文档加入转换器，添加后自动上传，上传完成点击开始转换，转换后即可下载查看。
                </blockquote>
                <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;color: #7ea08b;">
                    <i class="layui-icon layui-icon-notice"></i> 友情提示：转换器转换文件仅限于100M以内文件。
                </blockquote>
                <blockquote class="layui-elem-quote layui-text" style="margin-top: 15px;color: #7ea08b;">
                    <i class="layui-icon layui-icon-diamond"></i> 适用所有设备：在线文档转换器可完美适用于所有设备以及IE、Firefox、Chrome和Opera等热门浏览器。
                </blockquote>
                <button style="display: none" id="action" type="button" class="layui-btn">开始上传</button>
            </div>
        </div>
    </div>
</div>
</body>
<!-- 引入 jquery.js -->
<script src="/jquery/jquery-3.5.1.min.js"></script>
<!-- 引入 layui.js -->
<script src="/layui/layui.js"></script>
<script>
    layui.use(['upload', 'layer', 'element', 'form'], function(){
        var layer = layui.layer
            ,upload = layui.upload
            ,element = layui.element
            ,form = layui.form
        //拖拽上传
        var uploadInst = upload.render({
            elem: '#document'
            ,url: '/fileUpload'
            ,bindAction: '#action' //指向一个按钮触发上传
            ,accept: 'file' //普通文件
            ,acceptMime: 'application/pdf'
            ,size: 1024 * 100 //限定大小100m
            ,multiple: false
            ,data: {type: 1}
            ,auto: false
            ,choose: function(obj){
                var t = $("input[type='radio']:checked").val();
                var fileObject = obj.pushFile();
                if(Object.keys(fileObject).length>1){
                    promptBox(layer,'单次只能上传一个文件，请重新选择')
                }else {
                    obj.preview(function(index, file, result){
                        if((t==='1' || t==='2') && file.type!=='application/pdf'){
                            promptBox(layer,'无法上传，文件格式不是PDF')
                        }
                        else if(t==='3' && (file.type!=='application/msword' && file.type!=='application/vnd.openxmlformats-officedocument.wordprocessingml.document')){
                            promptBox(layer,'无法上传，文件格式不是Doc/Docx')
                        }else {
                        $("#name").text(file.name)
                        $("#action").click()
                        }
                    });
                }
            }
            ,before: function(obj){
                var t = $("input[type='radio']:checked").val();
                $("#document").hide()
                $("#choose").show()
                if(t==='1'||t==='2'){
                    $("#pdf").show()
                }else if(t==='3'){
                    $("#word").show()
                }
             }
            ,progress: function(n, elem, res, index){
                var percent = n + '%' //获取进度百分比
                element.progress('demo', percent);
            }
            ,done: function(res){
                if(res.result){
                    layer.msg('上传成功', {icon: 1});
                    $("#document").hide()
                    sessionStorage.setItem("originalName",res.originalName)
                }else {
                    promptBox(layer,'上传失败，请重试')
                }
            }
            ,error: function(){
                promptBox(layer,'上传失败，请重试')
            }
        });
        //刷新时处理初始数据
        if(sessionStorage.getItem("type")){
            var oldType = sessionStorage.getItem("type")
            $("input[name='type'][value='" + oldType + "']").attr("checked", true);
            form.render();
            reloadUpload(uploadInst,oldType)
        }else {
            sessionStorage.setItem("type","1")//默认1
        }
        deleteFile()
        // 监听radio类型
        form.on('radio(filter)', function(data){
            reload()
        })

        //开始转换事件
        $("#transform").click(function(){
            $("#step-1").hide()
            $("#step-2").show()
            var index = layer.load(1, {
                shade: [0.5,'#fff'] //0.1透明度的白色背景
                ,content: '转换中...'
                ,success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            $.ajax({
                //请求方式
                type : "POST",
                //请求地址
                url : "/transform",
                //数据，json字符串
                data : {originalName: sessionStorage.getItem("originalName"), type: $("input[type='radio']:checked").val()},
                //请求成功
                success : function(result) {
                    $("#step-2").hide()
                    $("#step-1").show()
                    if(result.result){
                      var t = $("input[type='radio']:checked").val();
                        layer.msg('转换成功', {icon: 1});
                        $("#reUpload").hide()
                        $(".layui-progress").hide()
                        $("#transform").hide()
                        $("#tip").show()
                        $("#compete").show()
                        $("#name").text(result.targetName)
                        if(t==='1'){
                            $("#pdf").hide()
                            $("#word").show()
                        }else if(t==='2'){
                            $("#pdf").hide()
                            $("#word").hide()
                            $("#zip").show()
                        }else if(t==='3'){
                            $("#word").hide()
                            $("#pdf").show()
                        }
                    }else {
                        layer.msg('转换失败，请重试或重新上传文档', {icon: 2});
                    }
                    layer.close(index)
                },
                //请求失败，包含具体的错误信息
                error : function(e){
                    layer.msg('转换失败，请重试或重新上传文档', {icon: 2});
                    layer.close(index)
                    $("#step-2").hide()
                    $("#step-1").show()
                }
            });
        })
        //下载
        $("#download").click(function(){
            // 用a标签接收
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = "/download?name="+sessionStorage.getItem("originalName")+"&type="+$("input[type='radio']:checked").val();
            a.click();
        })
        //删除
        $("#delete").click(function(){
            layer.confirm('确定删除？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                layer.close(layer.index)
                reload()
            });
        })
    });

    /**
     * 重新上传事件
     */
    function reUpload(){
        reload()
    }

    /**
     * 提示框
     */
    function promptBox(layer,msg){
        layer.alert(msg, {
            skin: 'layui-layer-molv' //样式类名
            ,closeBtn: 0
        }, function(){
            reload()
        });
    }

    /**
     * 刷新
     */
    function reload(){
        sessionStorage.setItem("type",$("input[type='radio']:checked").val())
        window.location.reload()
    }

    /**
     * 删除文件
     */
    function deleteFile(){
        if(sessionStorage.getItem("originalName")){
            $.ajax({
                //请求方式
                type : "POST",
                //请求地址
                url : "/delete",
                //数据，json字符串
                data : {originalName: sessionStorage.getItem("originalName")}
            });
            sessionStorage.removeItem("originalName");
        }
    }

    /**
     * 重载upload组件
     * @param uploadInst
     * @param value
     */
    function reloadUpload(uploadInst,value){
        if(value === '1'){
            sessionStorage.setItem("type",value)
            uploadInst.reload({
                acceptMime: 'application/pdf'
                ,data: {type: value}
                ,auto: false
            });
        }else if(value === '2'){
            sessionStorage.setItem("type",value)
            uploadInst.reload({
                acceptMime: 'application/pdf'
                ,data: {type: value}
                ,auto: false
            });
        }else if(value === '3'){
            sessionStorage.setItem("type",value)
            uploadInst.reload({
                acceptMime: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                ,data: {type: value}
                ,auto: false
            });
        }
    }
</script>
<style>
    @keyframes scaleDraw {
        /*定义关键帧、scaleDrew是需要绑定到选择器的关键帧名称*/
        0% {
            transform:scale(1);
            /*开始为原始大小*/
        }
        25% {
            transform:scale(1.1);
            /*放大1.1倍*/
        }
        50% {
            transform:scale(1);
        }
        75% {
            transform:scale(1.1);
        }
    }.conversion {
         margin-top: 15px;
         margin-bottom: 15px;
         background: #eaeaea;
         width:200px;
         height:200px;
         background-size:200px 200px;
         -webkit-animation-name:scaleDraw;
         /*关键帧名称*/
         -webkit-animation-timing-function:ease-in-out;
         /*动画的速度曲线*/
         -webkit-animation-iteration-count:infinite;
         /*动画播放的次数*/
         -webkit-animation-duration:2s;
         /*动画所花费的时间*/
     }
</style>
</html>
